package com.studyhub.question.service.impl;

import com.studyhub.question.mapper.AnswerMapper;
import com.studyhub.question.mapper.QuestionMapper;
import com.studyhub.question.model.dto.AnswerCreateDTO;
import com.studyhub.question.model.entity.QueAnswerEntity;
import com.studyhub.question.model.vo.AnswerVO;
import com.studyhub.question.service.AnswerService;
import com.studyhub.question.service.MailboxService;
import com.studyhub.web.utils.UserAuthUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 答案服务实现类
 */
@Service
@RequiredArgsConstructor
public class AnswerServiceImpl implements AnswerService {
    
    private final AnswerMapper answerMapper;
    private final QuestionMapper questionMapper;
    private final MailboxService mailboxService;
    
    @Override
    @Transactional
    public Long createAnswer(AnswerCreateDTO createDTO) {
        // 获取当前登录用户ID
        Integer userId = UserAuthUtil.getUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        
        // 创建答案实体
        QueAnswerEntity answer = new QueAnswerEntity();
        answer.setQuestionId(createDTO.getQuestionId());
        answer.setUserId(userId);
        
        // 处理parentAnswerId的精度问题
        if (createDTO.getParentAnswerId() != null && !createDTO.getParentAnswerId().isEmpty()) {
            try {
                // 将字符串类型的parentAnswerId转换为Long
                Long parentAnswerIdLong = Long.parseLong(createDTO.getParentAnswerId());
                answer.setParentAnswerId(parentAnswerIdLong);
            } catch (NumberFormatException e) {
                throw new RuntimeException("父级答案ID格式错误: " + createDTO.getParentAnswerId());
            }
        } else {
            answer.setParentAnswerId(null);
        }
        
        answer.setAtUserId(createDTO.getAtUserId());
        answer.setContent(createDTO.getContent());
        answer.setPublishTime(new Date());
        answer.setLikeCount(0);
        
        // 保存到数据库
        answerMapper.insert(answer);
        
        // 更新问题热度（有新回答增加热度）
        questionMapper.updateHotDegree(createDTO.getQuestionId(), 5);
        
        // 发送消息通知
        mailboxService.sendAnswerNotification(answer);
        
        return answer.getAnswerId();
    }
    
    @Override
    public List<AnswerVO> getQuestionAnswers(Long questionId) {
        // 查询所有顶级答案
        List<AnswerVO> topLevelAnswers = answerMapper.selectTopLevelAnswers(questionId);
        
        // 为每个顶级答案构建用户信息和递归构建子回复
        topLevelAnswers.forEach(answer -> {
            buildAnswerVO(answer);
            buildChildrenRecursively(answer);
        });
        
        return topLevelAnswers;
    }
    
    /**
     * 递归构建子回复
     */
    private void buildChildrenRecursively(AnswerVO parentAnswer) {
        // 查询当前答案的直接子回复
        List<AnswerVO> children = answerMapper.selectChildAnswers(parentAnswer.getAnswerId());
        
        if (children != null && !children.isEmpty()) {
            // 为每个子回复构建VO
            children.forEach(this::buildAnswerVO);
            
            // 递归构建子回复的子回复
            children.forEach(this::buildChildrenRecursively);
            
            // 设置子回复列表
            parentAnswer.setChildren(children);
        }
    }
    
    @Override
    @Transactional
    public void deleteAnswer(Long answerId) {
        // 获取当前用户ID
        Integer userId = UserAuthUtil.getUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        
        // 查询答案
        QueAnswerEntity answer = answerMapper.selectById(answerId);
        if (answer == null) {
            throw new RuntimeException("答案不存在");
        }
        
        // 检查是否为答案作者
        if (!answer.getUserId().equals(userId)) {
            throw new RuntimeException("只有答案作者才能删除答案");
        }
        
        // 删除答案（这里简化处理，实际项目中可能需要级联删除子回复）
        answerMapper.deleteById(answerId);
    }
    
    @Override
    @Transactional
    public void likeAnswer(Long answerId, boolean isLike) {
        // 获取当前用户ID
        Integer userId = UserAuthUtil.getUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        
        // 更新点赞数（这里简化处理，实际项目中需要防止重复点赞）
        int increment = isLike ? 1 : -1;
        answerMapper.updateLikeCount(answerId, increment);
    }
    
    /**
     * 构建答案VO对象
     */
    private void buildAnswerVO(AnswerVO answerVO) {
        // 设置answerIdStr，避免前端JavaScript精度丢失
        if (answerVO.getAnswerId() != null) {
            answerVO.setAnswerIdStr(answerVO.getAnswerId().toString());
        }
        
        // 用户信息已经在SQL中关联查询了
        // 这里可以进行额外的数据处理
        if (answerVO.getReplier() == null) {
            answerVO.setReplier(new AnswerVO.UserVO());
        }
        if (answerVO.getAtUser() == null) {
            answerVO.setAtUser(new AnswerVO.UserVO());
        }
    }
}
